import {
  BadRequestException,
  Injectable,
  NotFoundException,
} from '@nestjs/common';
import { CreateNormalUserDto } from './dto/create-normal-user.dto';
import { UpdateUserDto } from './dto/update-user.dto';
import { PrismaClient } from '@prisma/client';
import { LoginDto } from './dto/login-dto';
import * as argon2 from 'argon2';
import { JwtService } from '@nestjs/jwt';
import { Prisma } from 'prisma-binding';
@Injectable()
export class UserService extends PrismaClient {
  constructor(private readonly jwt: JwtService) {
    super();
  }
  async register(createUserDto: CreateNormalUserDto) {
    const user = await this.users.count({
      where: {
        OR: [
          {
            username: createUserDto.username,
          },
          {
            email: createUserDto.email,
          },
        ],
      },
    });
    if (!user) {
      createUserDto.password = await argon2.hash(createUserDto.password);
      const newUser = await this.users.create({
        data: createUserDto,
      });
      if (newUser) return '成功';
      throw new NotFoundException(`内部错误注册失败`);
    }
    throw new NotFoundException(`用户名或邮箱已存在`);
  }

  async login({ username, password }: LoginDto) {
    const user = await this.users.findUnique({
      where: { username },
    });
    if (!user) throw new BadRequestException('用户不存在');
    const psMatch = await argon2.verify(user.password, password);
    if (!psMatch) throw new BadRequestException('密码输入错误');

    delete user.password;
    // user.token = ;
    const token = await this.jwt.signAsync({
      username: user.username,
      iss: user.id,
    });
    return {
      ...user,
      access_token: token,
    };
  }

  logout() {
    return '退出成功';
  }

  async findAll(pageNum, pageSize, username, email) {
    const where = {};
    username ? (where['username'] = { contains: username }) : null;
    email ? (where['email'] = { contains: email }) : null;
    const list = await this.users.findMany({
      where: where,
      skip: (pageNum - 1) * pageSize,
      take: Number(pageSize),
    });
    const count = await this.users.count();
    return {
      list,
      count,
    };
  }

  findOne(id: number) {
    return `This action returns a #${id} user`;
  }

  update(id: number, updateUserDto: UpdateUserDto) {
    return `This action updates a #${id} user`;
  }

  remove(id: number) {
    return `This action removes a #${id} user`;
  }
}
